/*
 * @Author: your name
 * @Date: 2020-12-01 16:13:51
 * @LastEditTime: 2020-12-07 14:47:54
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \zw_site\plugins\cookie.js
 */
const Cookies = process.client ? require('js-cookie') : undefined

const getDomain = () => {
  if (process.env.NODE_ENV === 'development') {
    return location.hostname
  }
  return _domain || '.hzhrjj.com'
}

let _domain
let TokenKey
const HandleTimeKey = 'handletime'
export default function ({ $config }) {
  TokenKey = $config.tokenKey
  _domain = $config.domain
}

function get(key) {
  if (process.server) {
    return null
  }
  const domain = getDomain()
  return Cookies.get(key, { domain })
}

function set(key, value) {
  if (process.server) {
    return
  }
  const domain = getDomain()
  return Cookies.set(key, value, { domain })
}

export function getToken() {
  return get(TokenKey)
}

export function setToken(token) {
  if (!token) {
    return removeToken()
  }
  return set(TokenKey, token)
}

export function removeToken() {
  if (process.server) {
    return
  }
  const domain = getDomain()
  Cookies.remove(TokenKey)
  return Cookies.remove(TokenKey, { domain })
}

export function getDevice() {
  return get('device')
}

export function setDevice(device) {
  set('device', device)
}

export function cleanHandleTime() {
  if (process.server) {
    return
  }
  const domain = getDomain()
  Cookies.remove(HandleTimeKey)
  return Cookies.remove(HandleTimeKey, { domain })
}

export function getHandleTime() {
  return get(HandleTimeKey)
}

export function setHandleTime(value) {
  set(HandleTimeKey, value)
}

const StatTokenKey = 'stats-token'
export function getStatsToken() {
  return Cookies.get(StatTokenKey, { domain: getDomain() })
}

export function setStatsToken(token) {
  return Cookies.set(StatTokenKey, token, {
    domain: getDomain(),
    expires: 1,
    path: '/stats',
  })
}
